<template>
<div v-loading="loading">
    <div  class="func-set-content" v-if="moduleList.length">
        <FuncListItem :list="globalModuleList" @change-item="changeItem" :validate-tips="validateTipMap"></FuncListItem>
        <FuncListItem :list="moduleList" @change-item="changeItem" :validate-tips="validateTipMap"></FuncListItem>
    </div>
    <div class="common-save mt-20">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="loading">保存</el-button>
    </div>
</div>
</template>

<script setup>
import FuncListItem from '../part/func-set/func-list-item.vue'
import {ref, watch, defineProps, defineEmits} from 'vue'
import { useStore } from 'vuex';
import { useMessage } from '@/hooks/useMessage.js';
import { pageJump } from '@/global/location-transfer';

const store = useStore();
const {messageSuccess, messageError} = useMessage();

const emit = defineEmits(['updateInstitution', 'updateBrandId']);

const loading = ref(false);

const brandId = ref('');

const props = defineProps({
    currentTab: {
        type: String,
        default: ''
    },
    institutionInfo: {
        type: Object,
        default: () => {}
    }
});


watch(() => props.currentTab, (newVal) => {
    if (newVal === 'func') {
        moduleList.value = [];
        // console.log('func----brandId====', props.institutionInfo);
        brandId.value = props.institutionInfo.brandId;
        if(brandId.value){
            validateTipMap.value = {};
            getConfigData();
        }
    }
})


// 公共的全局模块
const globalModuleList = ref([]);

// 所有功能模块
const allModuleList = ref([]);

// 除全局外的其他功能模块
const moduleList = ref([]);

// 所有已经选中的
const checkedModuleList = ref([]);

// 所有已经选中的
const checkedModuleMap = ref({});

// 平级功能模块数据
const flatModuleList = ref([]);

// 错误提示
const validateTipMap = ref({});


function getConfigData() {
    loading.value = true;
    store.dispatch('proxyAction', {
        name: 'getSiteFuncDetail',
        queries: {
            brandId: brandId.value // 品牌id
        }
    }).then((res) => {
        loading.value = false;
        let globalList = [];
        let otherModuleList = [];

        allModuleList.value = res.data && res.data.brandModules || [];

        allModuleList.value.length && allModuleList.value.forEach(item => {
            if(item.moduleType === 'global') {
                globalList.push(item);
            }else{
                otherModuleList.push(item);
            }
        })

        globalModuleList.value = globalList || [];
        moduleList.value = otherModuleList || [];
        flatModuleList.value = initCheckData(allModuleList.value);
        checkedModuleList.value = flatModuleList.value.length && flatModuleList.value.filter(item => {
            fmtModuleLabel(item);
            if(item.checked) {
                checkedModuleMap.value[item.moduleKey] = item;
                return item;
            }
        })
    }).catch(err => {
        loading.value = false;
        console.log(err);
    })
}


// 选择数据
function changeItem(module) {
    let index = checkedModuleList.value.findIndex(item => {
        return item.moduleKey === module.moduleKey;
    })

    if(index > -1) {
        fmtModuleLabel(module);
        if(module.checked) {
            checkedModuleList.value[index] = module;
            checkedModuleMap.value[module.moduleKey] = module;
        }else{
            checkedModuleList.value.splice(index, 1);
            delete checkedModuleMap.value[module.moduleKey];
        }
       
    }else{
        fmtModuleLabel(module);
        if(module.checked) { 
            checkedModuleList.value.push(module);
            checkedModuleMap.value[module.moduleKey] = module;
        }
    }
    console.log('commit-checked===', checkedModuleList.value);
}




// 格式化标签为label的属性
function fmtModuleLabel(module) {
    if(module.moduleCheckType === 'label' && module.moduleRuleList && module.moduleRuleList.length && ['checkbox', 'radio'].includes(module.moduleRuleCheckType)) { // label属性
         let isChecked = module.moduleRuleList.some(item => {
             return item.checked;
         })
         module.checked = isChecked;
    }
}




// 递归遍历所有checked=true的数据
function initCheckData(list = [], parentItem={}, res = []) {
    list.length && list.forEach(item => {
        let tempItem = {
            id: item.id,
            moduleRuleList: item.moduleRuleList || undefined,
            moduleSort: item.moduleSort,
            moduleType: item.moduleType,
            parentId: item.parentId,
            moduleKey: item.moduleKey,
            moduleName: item.moduleName,
            checked: item.checked,
            needed: item.needed,
            moduleCheckType: item.moduleCheckType,
            moduleRuleCheckType: item.moduleRuleCheckType,
            parentModuleKey: parentItem ? parentItem.moduleKey : ''
        }
        res.push(tempItem);
        if(item.children && item.children.length) {

            initCheckData(item.children, item, res);
        }
    })
    return res;
}

// 保存所有选中的数据
function handleSave() {
    checkValidate();
}

function checkValidate() {
   validateTipMap.value = {};
   flatModuleList.value.length && flatModuleList.value.forEach(item => {
       let ruleList = checkedModuleMap.value[item.moduleKey] && checkedModuleMap.value[item.moduleKey].moduleRuleList && checkedModuleMap.value[item.moduleKey].moduleRuleList || [];
       let isHaveChecked = ruleList.length > 0 && ruleList.some(ruleItem => ruleItem.checked);
       if((item.needed && !item.parentModuleKey) || (item.needed && item.parentModuleKey && checkedModuleMap.value[item.parentModuleKey])) {
            if((ruleList.length > 0 && !isHaveChecked) || (ruleList.length <= 0 && !checkedModuleMap.value[item.moduleKey])) {
                 validateTipMap.value[item.moduleKey] = true;
            }
       }
   })
   if(Object.keys(validateTipMap.value).length === 0) {
       confirmSave();
   }else{
       messageError('请检查必填项');
   }
}

// 确定保存
function confirmSave() {
    loading.value = true
    store.dispatch('proxyAction', {
        name: 'updateSiteFuncDetail',
        data: {
            brandId: brandId.value, // 品牌id
            moduleConfigs: checkedModuleList.value || []
        }
    }).then((res) => {
        loading.value = false;
        messageSuccess('保存成功');
    }).catch(err => {
        loading.value = false;
        console.log(err);
    })
}

function cancel () {
    pageJump({ name: 'siteList' });
}

</script>

<style lang="scss" scoped>
.func-set-content{ 
    height: calc(100vh - 284px);
    overflow-y: auto;
}
.common-save {
    text-align: center;
    padding-top: 20px;
    border-top: 1px solid #eeeeee;
}

</style>